package sy.interceptor;

import javax.servlet.http.HttpSession;

import org.nutz.aop.InterceptorChain;
import org.nutz.aop.MethodInterceptor;
import org.nutz.dao.Dao;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.mvc.Mvcs;

import sy.annotation.MethodName;
import sy.bo.SessionInfo;
import sy.po.MethodLog;
import sy.po.User;
import sy.util.IpUtil;

/**
 * 动作方法拦截器，用于在访问mvc时记录一些日志
 * 
 * @author 孙宇
 *
 */
@IocBean(name = "actionLogInterceptor")
public class ActionLogInterceptor implements MethodInterceptor {

	@Inject("refer:dao")
	private Dao dao;

	@Override
	@Aop({ "transactionInterceptor" })
	public void filter(InterceptorChain chain) throws Throwable {
		MethodLog methodLog = new MethodLog();
		methodLog.setIp(IpUtil.getIp());
		methodLog.setFullName(chain.getCallingMethod().toString());
		methodLog.setEngName(chain.getCallingMethod().getName());
		MethodName methodName = chain.getCallingMethod().getAnnotation(MethodName.class);
		if (methodName == null) {
			methodLog.setName("未声明@MethodName注解");
		} else {
			methodLog.setName(methodName.name());
		}
		Object[] args = chain.getArgs();
		if (args != null && args.length > 0) {
			StringBuilder log = new StringBuilder();
			for (Object arg : args) {
				if (arg instanceof HttpSession) {
				} else {
					log.append(Json.toJson(arg));
				}
			}
			methodLog.setLog(log.toString());
		}
		HttpSession session = Mvcs.getHttpSession(false);
		if (session != null) {
			SessionInfo sessionInfo = (SessionInfo) session.getAttribute(SessionInfo.SESSIONINFONAME);
			if (sessionInfo != null) {
				User u = sessionInfo.getUser();
				if (u != null) {
					methodLog.setUserName(u.getName());
					methodLog.setCompanyId(u.getCompanyId());
				}
			}
		}
		dao.insert(methodLog);// 存入一些自己拦截的日志信息
		chain.doChain();// 继续执行其他拦截器
	}

}
